<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 手机短信接口
 */
class Advertisers extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    protected $app_id = null;
    protected $secret = null;
    protected $auth_code = null;
    protected $domain = null;
    protected $state = null;
    protected $Advertisersauth = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->domain = 'ads.tiktok.com';
        $this->app_id = '6940196039722795010';
        $this->secret = '784153f9137628c75d2e3d501a228cae38ec065f';
    }

    public function oauth2callback()
    {
        $this->auth_code = $this->request->request('auth_code');
        $this->state = $this->request->request('state');
        $access_token = $this->AccessToken();
        if(!$access_token){
            $this->error('access_token为空');
        }else{
            //记录access_token
             $params['createtime'] = time();
             $params['updatetime'] = time();
             $params['auth_code'] = $this->auth_code;
             $params['state'] = $this->state;
             $params['access_token'] = $access_token;
             $result = Db::name('advertisers_auth') ->insert($params, true);
             if ($result) {
                 $this->success('授权成功',$access_token);
             } else {
                 $this->error('授权失败');
             }
        }
    }
    /**
     * 获取Access token
     */
    /**
     * 生成Access token
     */
    public function AccessToken()
    {
        $url = 'https://'.$this->domain.'/open_api/v1.2/oauth2/access_token/';
        $data['app_id'] = $this->app_id;
        $data['auth_code'] = $this->auth_code;
        $data['secret'] = $this->secret;
        $result = $this->posturl($url,$data);
        $result = json_decode($result,true);
        if($result['code'] == 0){
            $access_token = $result['data']['access_token'];
            return $access_token;
        }else{
            return null;
        }
    }
    /**
     * 获取可访问的广告主列表
     */
    public function GetAdvertiser()
    {
        $access_token = $this->request->request('access_token');
        if (empty($access_token)) {
            $this->error('access_token为空');
        }
        $url = 'https://'.$this->domain.'/open_api/v1.2/oauth2/advertiser/get/';
        $url = $url.'?access_token='.$access_token.'&app_id='.$this->app_id.'&secret='.$this->secret;
        $result = $this->geturl($url);
        $result = json_decode($result,true);
        if($result['code'] == 0){
            $list = $result['data']['list'];
            if(empty($list)){
                $this->error('暂无数据');
            }else{
                $this->success('返回数据', $list);
            }
        }else{
            $this->error($result['message']);
        }
    }


    /**
     * 获取可访问的广告主列表
     */
    public function pixel_track()
    {
//        http://zhtest.dnssystem.cn/api/advertisers/pixel_track?access_token=98b05c50e008b77f2486411b1fc8f7309d177e39&pixel_code=C3OFPSG4C3SCJI4R2N1G
//        C3OFPSG4C3SCJI4R2N1G
        $access_token = $this->request->request('access_token');
        if (empty($access_token)) {
            $this->error('access_token为空');
        }
        $pixel_code = $this->request->request('pixel_code');
        $url = 'https://'.$this->domain.'/open_api/v1.2/pixel/track/';
        $data['pixel_code'] = $pixel_code;
        $AccessToken = 'Access-Token:'.$access_token;

        //测试
        $callback = $this->request->request('callback');
        if (empty($callback)) {
            $this->error('ttlid为空');
        }
//        $callback = 'E.C.P.CoMBt_qbMcirLn3m3mnqyzdduxtk9CYOSuwO-nVYb2hRHOInBa6T3bDrX4_c5Xq2yvBO3RzX20BnQ3f-7ez6ySjbdE6xhF21mfIAQhlhuiiGRnamZoKyXvLuab2EoHGUttFe_NZulLEmIrXBJBYe4syBaMmmfsEGwusEDEF8i_kTZylaEUgSBHYyLjAaIJRz7J9IHm4nYTfLphZiPO6UimTnbvGTuzwRPX1wok3Q';
        $email[0]['phone_number'] = '5814452001';
        $email[0]['email'] = 'mlle.val@hotmail.com';
        foreach ($email as $item) {
            // $context['user']['phone_number'] = $this->encrypt_sha256($item['phone_number']);
            // $context['user']['email'] = $this->encrypt_sha256($item['email']);
            $context['ad']['callback'] = $callback;
            $data['context'] = json_encode($context);
//            浏览
            $data['event'] = 'ViewContent';
            $result = $this->posturl($url,$data,$AccessToken);
//            加购
             $data['event'] = 'AddToCart';
             $result = $this->posturl($url,$data,$AccessToken);
            //            购买
            $data['event'] = 'Checkout';
            $result = $this->posturl($url,$data,$AccessToken);
//             支付成功
            $data['event'] = 'Purchase';
            $result = $this->posturl($url,$data,$AccessToken);
        }
        if (!empty($result)) {
            $result = json_decode($result,true);
            $this->success('返回数据', $result);
        } else {
            $this->success('暂无接口调用');
        }

    }

    public function encrypt_sha256($str){
        return hash("sha256", $str);
    }

    public function add_success_ajax()
    {
        //允许跨域访问
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:POST');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        $ttclid = $this->request->post("ttclid");
        $url = $this->request->post("url");
        dump($ttclid);
        dump($url);
        die;

        if(!empty($SensitiveIpAddress['url']) && $SensitiveIpAddress['url'] == $pathnames && !empty($pathnames)){
            $return['status'] = true;
            $return['msg'] = '本页面无需跳转';
            return json($return);
        }
        if(!empty($SensitiveIpAddress)){
            $return['status'] = false;
            $return['msg'] = 'The IP address is illegal';
            $return['data'] = array();
            $return['url'] = $SensitiveIpAddress['url'];
            return json($return);
        }
        return json($return);
    }

    /**
     * 获取广告主信息
     */
    public function InfoAdvertiser()
    {
        $access_token = $this->request->request('access_token');
        if (empty($access_token)) {
            $this->error('access_token为空');
        }
        $url = 'https://'.$this->domain.'/open_api/v1.2/advertiser/info/';

        $advertiser_ids = ['6966922944106790914'];//格式
        $advertiser_ids = json_encode($advertiser_ids);
        $url = $url.'?advertiser_ids='.$advertiser_ids;

        $fields = [];
//        $fields = ['telephone'];//格式
        if(!empty($fields)){
            $fields = json_encode($fields);
            $url = $url.'&fields='.$fields;
        }
        $AccessToken = 'Access-Token:'.$access_token;
        $result = $this->geturl($url,$AccessToken);
        $result = json_decode($result,true);
        if($result['code'] == 0){
            $data = $result['data'];
            if(empty($data)){
                $this->error('暂无数据');
            }else{
                $this->success('返回数据', $data);
            }
        }else{
            $this->error($result['message']);
        }
    }

    /**
     * 投放推广系列之后，可以获取推广系列的相关信息以及状态。
     */
    public function CampaignGet()
    {
        $access_token = $this->request->request('access_token');
        if (empty($access_token)) {
            $this->error('access_token为空');
        }
        $url = 'https://'.$this->domain.'/open_api/v1.2/campaign/get/';

        $advertiser_id = '6966922944106790914';//格式
        $url = $url.'?advertiser_id='.$advertiser_id;

        $fields = [];
//        $fields = ['telephone'];//格式
        if(!empty($fields)){
            $fields = json_encode($fields);
            $url = $url.'&fields='.$fields;
        }
        $AccessToken = 'Access-Token:'.$access_token;
        $result = $this->geturl($url,$AccessToken);
        $result = json_decode($result,true);
        if($result['code'] == 0){
            $data = $result['data'];
            if(empty($data)){
                $this->error('暂无数据');
            }else{
                $this->success('返回数据', $data);
            }
        }else{
            $this->error($result['message']);
        }
    }

    /**
     * 获取广告组列表
     */
    public function AdgroupGet()
    {
        $access_token = $this->request->request('access_token');
        if (empty($access_token)) {
            $this->error('access_token为空');
        }
        $url = 'https://'.$this->domain.'/open_api/v1.2/adgroup/old_get/';

        $advertiser_id = '6966922944106790914';//格式
        $url = $url.'?advertiser_id='.$advertiser_id;

        $fields = [];
//        $fields = ['telephone'];//格式
        if(!empty($fields)){
            $fields = json_encode($fields);
            $url = $url.'&fields='.$fields;
        }
        $AccessToken = 'Access-Token:'.$access_token;
        $result = $this->geturl($url,$AccessToken);
        $result = json_decode($result,true);
        if($result['code'] == 0){
            $data = $result['data'];
            if(empty($data)){
                $this->error('暂无数据');
            }else{
                $this->success('返回数据', $data);
            }
        }else{
            $this->error($result['message']);
        }
    }

    /**
     * 获取自定义广告及程序化广告的相关信息以及状态
     */
    public function AdGet()
    {
        $access_token = $this->request->request('access_token');
        if (empty($access_token)) {
            $this->error('access_token为空');
        }
        $url = 'https://'.$this->domain.'/open_api/v1.2/ad/get/';

        $advertiser_id = '6966922944106790914';//格式
        $url = $url.'?advertiser_id='.$advertiser_id;

        $fields = [];
//        $fields = ['telephone'];//格式
        if(!empty($fields)){
            $fields = json_encode($fields);
            $url = $url.'&fields='.$fields;
        }
        $AccessToken = 'Access-Token:'.$access_token;
        $result = $this->geturl($url,$AccessToken);
        $result = json_decode($result,true);
        if($result['code'] == 0){
            $data = $result['data'];
            if(empty($data)){
                $this->error('暂无数据');
            }else{
                $this->success('返回数据', $data);
            }
        }else{
            $this->error($result['message']);
        }
    }

    /**
     * 获取自定义广告及程序化广告的相关信息以及状态
     */
    public function AdDynamicGet()
    {
        $access_token = $this->request->request('access_token');
        if (empty($access_token)) {
            $this->error('access_token为空');
        }
        $url = 'https://'.$this->domain.'/open_api/v1.2/ad/dynamic/get/';

        $advertiser_id = '6966922944106790914';//格式
        $url = $url.'?advertiser_id='.$advertiser_id;
        $adgroup_ids = [1700938198982657,1700938020429873,1700931817528337,1700931816034322,1700931816033330,1700939682867233,1700938215554082,1700938103753729,1700938195622962,1700938195622930];//格式
        $adgroup_ids = json_encode($adgroup_ids);
        $url = $url.'&adgroup_ids='.$adgroup_ids;

        $fields = [];
//        $fields = ['telephone'];//格式
        if(!empty($fields)){
            $fields = json_encode($fields);
            $url = $url.'&fields='.$fields;
        }
        $AccessToken = 'Access-Token:'.$access_token;
        $result = $this->geturl($url,$AccessToken);
        $result = json_decode($result,true);
        if($result['code'] == 0){
            $data = $result['data'];
            if(empty($data)){
                $this->error('暂无数据');
            }else{
                $this->success('返回数据', $data);
            }
        }else{
            $this->error($result['message']);
        }
    }

    /**
     * 报表管理
     */
    public function ReportsGet()
    {
        $access_token = $this->request->request('access_token');
        if (empty($access_token)) {
            $this->error('access_token为空');
        }
        $url = 'https://'.$this->domain.'/open_api/v1.2/reports/integrated/get/';

        $advertiser_id = '6966922944106790914';//格式
        $url = $url.'?advertiser_id='.$advertiser_id;

//        $service_type = 'AUCTION';//广告服务类型。可选值: 竞价广告 AUCTION, 品牌广告 RESERVATION， 默认值: AUCTION
        $report_type = 'BASIC';//报表类型。可选值: 基础报表 BASIC, 受众分析报表 AUDIENCE，试玩素材报表 PLAYABLE_MATERIAL，DPA报表 CATALOG，详见下文【枚举值-报表类型】。当 service_type=RESERVATION 时，仅支持基础报表
        $url = $url.'&report_type='.$report_type;

        $data_level = '';//string 报表数据层级。当 report_type 为 BASIC、AUDIENCE 或 CATALOG 时必填。可选值: AUCTION_AD,AUCTION_ADGROUP,AUCTION_ADVERTISER,AUCTION_CAMPAIGN,RESERVATION_AD,RESERVATION_ADGROUP,RESERVATION_ADVERTISER,RESERVATION_CAMPAIGN
        $url = $url.'&data_level='.$data_level;

        $dimensions = '';//string[] 列表分组条件。竞价广告和合约广告支持不同的 dimensions，枚举及支持的组合见【竞价广告报表说明-支持的维度】 和 【合约广告报表说明-支持的维度】 ，举例：["campaign_id", "stat_time_day"] 表示同时按照 campaign_id 和 stat_time_day（天）分组 注意：当 dimensions 包含 stat_time_day 时，查询时间范围不能超过 30 天，当 dimensions 包含 stat_time_hour 时，查询时间范围不能超过 1 天
        $url = $url.'&dimensions='.$dimensions;

        $start_date = '';//string 查询起始日期，闭区间。日期需要根据广告主时区设定。格式如：2020-01-01，lifetime为false 时必填
        $url = $url.'&start_date='.$start_date;

        $end_date = '';//string 查询结束日期，闭区间。日期需要根据广告主时区设定。格式如：2020-01-01，lifetime为false 时必填
        $url = $url.'&end_date='.$end_date;

        $fields = [];
//        $fields = ['telephone'];//格式
        if(!empty($fields)){
            $fields = json_encode($fields);
            $url = $url.'&fields='.$fields;
        }
        $AccessToken = 'Access-Token:'.$access_token;
        $result = $this->geturl($url,$AccessToken);
        if($result){
            $result = json_decode($result,true);
            if($result['code'] == 0){
                $data = $result['data'];
                if(empty($data)){
                    $this->error('暂无数据');
                }else{
                    $this->success('返回数据', $data);
                }
            }else{
                $this->error($result['message']);
            }
        }else{
            $this->error('接口错误');
        }

    }

    function geturl($url,$AccessToken=null){
        $headerArray =array("Content-type:application/json;","Accept:application/json");
        if(!empty($AccessToken)){
            $headerArray[] = $AccessToken;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    function posturl($url,$data = array(),$AccessToken=null){
        $data = (is_array($data)) ? json_encode($data,JSON_UNESCAPED_UNICODE) : $data;
        $headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");
        if(!empty($AccessToken)){
            $headerArray[] = $AccessToken;
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    function puturl($url,$data = array()){
        $data = (is_array($data)) ? json_encode($data,JSON_UNESCAPED_UNICODE) : $data;
        $ch = curl_init(); //初始化CURL句柄
        curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL
        curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //设为TRUE把curl_exec()结果转化为字串，而不是直接输出
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"PUT"); //设置请求方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置提交的字符串
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    function delurl($url){
        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL,$url);
        curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    function patchurl($url,$data = array()){
        $data = (is_array($data)) ? json_encode($data,JSON_UNESCAPED_UNICODE) : $data;
        $ch = curl_init();
        curl_setopt ($ch,CURLOPT_URL,$url);
        curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}
